package cn.bugstack.mybatis.executor.resultset;

import cn.bugstack.mybatis.executor.Executor;
import cn.bugstack.mybatis.mapping.BoundSql;
import cn.bugstack.mybatis.mapping.MappedStatement;
import cn.bugstack.mybatis.session.ResultHandler;

import java.lang.reflect.Method;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;



public class DefaultResultSetHandler implements ResultSetHandler{

    private final Executor executor;
    private final MappedStatement mappedStatement;
    private final ResultHandler resultHandler;
    private final BoundSql boundSql;

    public DefaultResultSetHandler(Executor executor, MappedStatement mappedStatement, ResultHandler resultHandler, BoundSql boundSql) {
        this.executor = executor;
        this.mappedStatement = mappedStatement;
        this.boundSql = boundSql;
        this.resultHandler = resultHandler;
    }

    @Override
    public <E> List<E> handleResultSets(Statement stmt) throws SQLException {
        ResultSet resultSet = stmt.getResultSet();
        String resultType = mappedStatement.getBoundSql().getResultType();
        Class<?> aClass = null;
        try {
            aClass = Class.forName(resultType);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return resultSet2Obj(resultSet,aClass);
    }

    private <T> List<T> resultSet2Obj(ResultSet resultSet, Class clazz) {
        List<T> list = new ArrayList<T>();
        try {
            ResultSetMetaData rmsd = resultSet.getMetaData();
            int columnCount = rmsd.getColumnCount();
            while (resultSet.next()){
                T obj = (T) clazz.newInstance();
                for (int i = 1; i <= columnCount; i++) {
                    Object value = resultSet.getObject(i);
                    String columnName = rmsd.getColumnName(i);
                    String methodName = "set"+columnName.substring(0,1).toUpperCase()+columnName.substring(1);
                    Method method;
                    if(value instanceof Timestamp){
                        method = clazz.getMethod(methodName,java.util.Date.class);
                    }else{
                        method = clazz.getMethod(methodName,value.getClass());
                    }
                    method.invoke(obj,value);
                }
                list.add(obj);
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        return list;
    }


}
